package web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/*登录验证的过滤器*/
@WebFilter("/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String[] urls = {"/login.jsp","/imgs/","/css/","/register.jsp","/register","/LoginServlet","/ckeckCodeServlet"};
        String url = req.getRequestURL().toString();
        for(String u:urls)
        {
            if(url.contains(u))
            {
                chain.doFilter(request, response);
                return;
            }
        }
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if(user == null)
        {
            req.setAttribute("msg","您尚未登录！！！");
            req.getRequestDispatcher("/login.jsp").forward(req,response);
        }
        else
        chain.doFilter(request, response);

    }
}
